# coding:utf-8
class Terminal < ActiveRecord::Base
  has_paper_trail :version => :paper_trail_version, :versions => :paper_trail_versions
  include TrafficConvert
  attr_accessor :total_flow
  has_one :terminal_info
  has_one :terminal_order
  has_one :terminal_user, :through => :terminal_order
  has_many :traffics, as: :device
  belongs_to :terminal_version
  belongs_to :terminal_group, counter_cache: true
  belongs_to :recommander, class_name: 'Account'
  has_many :register_accounts,:foreign_key => :register_terminal_id,:class_name => 'Account'
  has_many :recommands
  validates :mac, format: { with: /\A([a-f0-9]{2}:){5}[a-f0-9]{2}\z/ }, uniqueness: true

  validates_presence_of :mac
  #validates_presence_of :imei,:sim_iccid,:if => Proc.new{|t| t.terminal_order.name == 'yidong' },:on => :update

  scope :by_address, lambda {|address| joins(:terminal_user).where(["terminal_users.address like ? or terminal_users.car_license like ?", '%'+address+'%', '%'+address+'%'])}
  scope :by_user, lambda {|user| joins(:terminal_user).where(["terminal_users.name like ?", '%'+user+'%'])}
  
  scope :by_name, lambda {|name| joins(:terminal_order).where(["terminal_orders.name = ?", name])}

  before_validation do
    mac.downcase!
    add_mac_colon!
  end

  # def terminal_order_name
  #   self.terminal_order.try(:name)
  # end

  before_save do
    self.is_latest = (TerminalVersion.latest == version) if version_changed?
    true
  end

  def to_s
    info = case self.terminal_order.try(:name)
    when 'yidong' then [self.terminal_user.try(:car_unit),dispaly_address].join(" ")
    when 'zengqiang' then [self.terminal_user.try(:user_unit),dispaly_address].join(" ")
    end
    terminal_group ? "[#{terminal_group}]: #{info} #{mac}" : "#{info} #{mac}"
  end

  # fix the counter cache in rails 3, rails4 has fix the counter_cache.
  # this is not a complete way .
  before_save :fix_counter_cache, :if => ->(er) { !er.new_record? && er.terminal_group_id_changed? }

  def dispaly_driver_phones
    [self.terminal_user.driver_phone,self.terminal_user.driver_phone2].join("\n") if self.terminal_user
  end

  def dispaly_order_name
    'Y-BOX' + (self.terminal_order.try(:name) == 'yidong' ? '移动版' : '加强版')
  end

  def total_account_signin
    AccountSignin.count(:id,:conditions => ["account_signins.terminal_id = ?",self.id])
  end

  def total_register
    AccountSignin.count(:account_id,:distinct => true,:conditions => ["account_signins.terminal_id = ?",self.id])
  end

  def dispaly_address
    case self.terminal_order.try(:name)
    when 'yidong'
      self.terminal_order.terminal_user.car_license
    when 'zengqiang'
      self.terminal_order.terminal_user.address
    end
  end

  def display_in_tree
    "#{self.order_name} #{self.mac} #{self.terminal_user.try(:name)}"
  end

  # add colon seperator to mac address
  def add_mac_colon!
    unless mac.include? ':'
      self.mac = mac.to_s.chars.each_slice(2).map(&:join).join(':')
    end
  end

  def current_traffic
    traffics.sum(:flow,:conditions => ["created_at <= ? and created_at >= ?",Time.now.end_of_month,Time.now.beginning_of_month])
  end

  def left_traffic
    case self.terminal_order.try(:name)
    when 'yidong'
      max_traffic = traffic_flow_from_params Settings.max_traffic
      max_traffic - current_traffic
    else
      "NA"
    end
  end

  def is_traffic_warning
    max_traffic = traffic_flow_from_params Settings.max_traffic
    warning_rate = 0.8
    (total_flow.to_f / max_traffic ) > warning_rate
  end

  private

  def fix_counter_cache
    if self.valid?
      TerminalGroup.decrement_counter(:terminals_count, self.terminal_group_id_was)
      TerminalGroup.increment_counter(:terminals_count, self.terminal_group_id)
    end
  end

end
